package com.fuchen.academic.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

import com.fuchen.academic.constants.Const;

public class SessionFilter extends OncePerRequestFilter {

	private static final String[] ALLOW_URLS = {
		"/competition/detail",
		"/schoolLogo","/index.html","/competition/queryByPage","/login","/index","/left","/right","/main","/head","/menu","/tail","/signup",".js",".css",".jpg",".png",".gif",".pdf",".rar"
	};
	
	@Override
	protected void doFilterInternal(HttpServletRequest req,
			HttpServletResponse resp, FilterChain chain)
			throws ServletException, IOException {

		String uri = req.getRequestURI();
		
		boolean doFilter = true;
		
		for(String url : ALLOW_URLS){
			if(uri.endsWith(url)){
				doFilter = false;
				break;
			}
		}
		
		if(doFilter){
			Object users = req.getSession().getAttribute(Const.CURRENT_USER);
			if(null == users){
				if(uri.indexOf("/front/")!=-1){
					resp.sendRedirect(req.getServletContext().getContextPath()+"/front/login");
				}else{
					resp.sendRedirect(req.getServletContext().getContextPath()+"/login");
				}
				
			}
			else
			{
				chain.doFilter(req, resp);
			}
		}else{
			chain.doFilter(req, resp);
		}
		
	}

}
